<template>
  <div class="chartarea">
    <div :id="chartData.id" class="echart"></div>
  </div>
</template>

<script>
import echarts from "@/utils/lib/echarts";
import { GaugeChart } from "echarts/charts";
echarts.use([GaugeChart]);
export default {
  name: "environmentGaugechart",
  props: {
    // 图数据
    chartData: {
      type: Object,
      default: {},
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    this.getChartsdata(this.chartData);
  },
  beforeDestroy() {
    this.chartDes();
  },
  watch: {
    chartData: {
      handler(val) {
        if (val) {
          // this.chartDes();
          // this.getChartsdata(this.chartData);
        }
      },
      deep: false,
      immediate: false,
    },
  },
  methods: {
    chartDes() {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    getChartsdata(chartData) {
      let option = {
        tooltip: {
          formatter: "{a} <br/>{b} : {c}" + chartData.unit,
        },
        series: [
          {
            name: "温湿度",
            type: "gauge",
            min: chartData.min,
            max: chartData.max,
            detail: {
              formatter: "{value} " + chartData.unit,
              fontSize: 12,
            },
            data: [
              {
                value: chartData.data,
                name: chartData.name,
              },
            ],
          },
        ],
      };
      this.initChart(chartData.id, option);
    },
    initChart(id, options) {
      this.chart = echarts.init(document.getElementById(id));
      this.chart.setOption(options);
      window.addEventListener("resize", () => {
        if (this.chart) {
          this.chart.resize();
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.chartarea {
  .echart {
    width: 100%;
    height: 280px;
  }
}
</style>
